package com.woniuxy.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.exception.CartException;
import com.woniuxy.commons.exception.code.CartExceptionCode;
import com.woniuxy.commons.utils.BeanCopyUtil;
import com.woniuxy.controller.form.AddCartForm;
import com.woniuxy.controller.form.DelCartForm;
import com.woniuxy.dao.model.CartInfo;
import com.woniuxy.dao.CartInfoDao;
import com.woniuxy.service.CartInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.dto.AllCartListDto;
import com.woniuxy.service.dto.UserDetailsDto;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author psy
 * @since 2022-06-28
 */
@Service
public class CartInfoServiceImpl extends ServiceImpl<CartInfoDao, CartInfo> implements CartInfoService{
    @Resource
    private CartInfoService cartInfoService;
    @Resource
    private RedisTemplate<String,String> sot;

    @Override
    public Boolean addCart(AddCartForm addCartForm) throws JsonProcessingException {
        CartInfo cartInfo = BeanCopyUtil.copyOne(addCartForm, CartInfo.class);
        boolean b = cartInfoService.saveOrUpdate(cartInfo);
        if(b){
            List<CartInfo> customerId = cartInfoService.list(new QueryWrapper<CartInfo>().eq("customerId", addCartForm.getCustomerId()));
            List<AllCartListDto> allCartListDtos = BeanCopyUtil.copyList(customerId, AllCartListDto.class);
            //新增购物车则将加入的数据同步到redis中
            ObjectMapper om=new ObjectMapper();
            String s = om.writeValueAsString(allCartListDtos);
            sot.opsForValue().set(addCartForm.getCustomerId()+"",s);
            return true;
        }else{
            throw new CartException(CartExceptionCode.CART_ADD_FAIL.getCode(),CartExceptionCode.CART_ADD_FAIL.getMessage());
        }
    }

    @Override
    public ArrayList<AllCartListDto> getAllCartsByCustomerId(Long customerId) throws JsonProcessingException {
        List<CartInfo> customerId1 = cartInfoService.list(new QueryWrapper<CartInfo>().eq("customerId", customerId));
        if(null==customerId1){
            return null;
        }else{
            ArrayList<AllCartListDto> allCartListDtos = (ArrayList<AllCartListDto>)BeanCopyUtil.copyList(customerId1, AllCartListDto.class);
            RedisAddByListJson(allCartListDtos,customerId);
            String o = (String)sot.opsForValue().get(customerId + "");
            ArrayList<AllCartListDto> allCartListDtos1 = (ArrayList<AllCartListDto>) JSONObject.parseArray(o, AllCartListDto.class);

            return allCartListDtos;
        }
    }

    @Override
    public void RedisAddByObjectJson(Object o,Long id) throws JsonProcessingException {
        ObjectMapper om=new ObjectMapper();
        String s = om.writeValueAsString(o);
        sot.opsForValue().set(id+"",s);
    }

    @Override
    public void RedisAddByListJson(List list,Long id) throws JsonProcessingException {
        ObjectMapper om=new ObjectMapper();
        String s = om.writeValueAsString(list);
        sot.opsForValue().set(id+"",s);
    }

    @Override
    public Boolean delCart(DelCartForm delCartForm) throws JsonProcessingException {
        boolean remove = cartInfoService.remove(new QueryWrapper<CartInfo>().eq("customerId", delCartForm.getCustomerId()).eq("foodName", delCartForm.getFoodName()));
        if(remove){
            List<CartInfo> customerId = cartInfoService.list(new QueryWrapper<CartInfo>().eq("customerId", delCartForm.getCustomerId()));
            List<AllCartListDto> allCartListDtos = BeanCopyUtil.copyList(customerId, AllCartListDto.class);
            //删除购物车则将删除后的数据同步到redis中
            RedisAddByListJson(allCartListDtos,delCartForm.getCustomerId());
            return true;
        }else{
            throw new CartException(CartExceptionCode.CART_DEL_FAIL.getCode(),CartExceptionCode.CART_DEL_FAIL.getMessage());
        }
    }

    @Override
    public Boolean delCarts(Long id, String storeName) throws JsonProcessingException {
        boolean remove = cartInfoService.remove(new QueryWrapper<CartInfo>().eq("customerId", id).eq("storeName", storeName));
        String s = sot.opsForValue().get(id + "");
        ArrayList<AllCartListDto> allCartListDtos = (ArrayList<AllCartListDto>) JSONObject.parseArray(s, AllCartListDto.class);
        Iterator<AllCartListDto> iterator = allCartListDtos.iterator();
        while (iterator.hasNext()) {
            if(iterator.next().getStoreId()==id){
                iterator.remove();
            }
        }
        ObjectMapper om=new ObjectMapper();
        String s1 = om.writeValueAsString(allCartListDtos);
        sot.opsForValue().set(id+"",s1);
        if(remove){
            return true;
        }else{
            throw new CartException(CartExceptionCode.CARTS_DEL_FAIL.getCode(),CartExceptionCode.CARTS_DEL_FAIL.getMessage());
        }
    }

    @Override
    public ArrayList<AllCartListDto> loadStoreByStore(String storeName) {
        List<CartInfo> storeName1 = cartInfoService.list(new QueryWrapper<CartInfo>().eq("storeName", storeName));
        if(null==storeName1){
            return null;
        }else{
            ArrayList<AllCartListDto> allCartListDtos = (ArrayList<AllCartListDto>)BeanCopyUtil.copyList(storeName1, AllCartListDto.class);
            return allCartListDtos;
        }
    }

    @Override
    public AllCartListDto findCart(String foodName) throws JsonProcessingException {
        CartInfo foodName1 = cartInfoService.getOne(new QueryWrapper<CartInfo>().eq("foodName", foodName));
        if(null==foodName1){
            return null;
        }else{
            //将已有的菜品直接数量加1
            System.out.println("++++++");
            int num1=foodName1.getNum()+1;
            double price=foodName1.getFoodPrice()*(num1);
            boolean update = cartInfoService.update(new UpdateWrapper<CartInfo>().eq("foodName", foodName).set("num", num1).set("price", price));
            UserDetailsDto userDetailsDto = (UserDetailsDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Long id = userDetailsDto.getId();
            String s = sot.opsForValue().get(id + "");
            ArrayList<AllCartListDto> allCartListDtos = (ArrayList<AllCartListDto>) JSONObject.parseArray(s, AllCartListDto.class);
            for (AllCartListDto allCartListDto : allCartListDtos) {
                if(allCartListDto.getFoodName().equals(foodName)){
                    allCartListDto.setNum(num1);
                    allCartListDto.setPrice(price);
                }
            }
            ObjectMapper om=new ObjectMapper();
            String s1 = om.writeValueAsString(allCartListDtos);
            sot.opsForValue().set(id+"",s1);
            foodName1.setNum(num1);
            foodName1.setPrice(price);
            AllCartListDto allCartListDto = BeanCopyUtil.copyOne(foodName1, AllCartListDto.class);
            return allCartListDto;
        }
    }


}
